/*************************************************************************
  > File Name: 3.server.c
  > Author: Ykk
  > Mail: 3393579535@qq.com 
  > Created Time: 2023年05月16日 星期二 20时58分28秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>

int main()
{
	//创建套接字
	int lis_fd = socket(AF_INET,SOCK_STREAM,0);
	int ret = -1;
	if(-1 == lis_fd)
	{
		perror("socket");
		return 1;
	}
	else
	{
		printf("创建套接字成功...\n");
	}
	//绑定
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(8000);
	//addr.sin_addr.s_addr = INADDR_ANY;//绑定的是通配地址，通配地址是本机所有ip
	inet_pton(AF_INET,"192.168.152.129",&addr.sin_addr.s_addr);
	ret = bind(lis_fd,(struct sockaddr *)&addr,sizeof(addr));
	if(-1 == ret)
	{
		perror("bind");
		return 1;
	}
	else
	{
		printf("绑定成功....\n");
	}
	//监听
	ret = listen(lis_fd,128);
	if(-1 == ret)
	{
		printf("监听失败...\n");
	}
	else
	{
		printf("监听成功...\n");
	}
	//提取
	struct sockaddr_in cliaddr;
	int cli_fd;
	socklen_t len = sizeof(cliaddr);
	cli_fd = accept(lis_fd,(struct sockaddr *)&cliaddr,&len);
	char ip[16]="";
	if(-1 == cli_fd)
	{
		perror("accept");
		return 1;
	}
	else
	{
		printf("客户端%s,port:%d连接成功...\n",inet_ntop(AF_INET,&cliaddr.sin_addr.s_addr,ip,16),
				                                      ntohs(cliaddr.sin_port));
	}
	//读写
	char buf[1024] = "";
	while(1)
	{
		bzero(buf,sizeof(buf));
		int n = read(cli_fd,buf,sizeof(buf));
		write(STDOUT_FILENO,buf,n);
		n = read(STDIN_FILENO,buf,sizeof(buf));
		write(cli_fd,buf,n);
	
	}
	//关闭
	close(lis_fd);
	close(cli_fd);
	return 0;
}
